<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <el-tabs>
          <el-tab-pane label="角色管理">
            <el-row>
              <el-button type="primary" size="small" class="el-icon-plus addbtn" @click="AddshowFn">新增角色</el-button>
            </el-row>
            <el-table
              :data="$store.state.role.Allroles.rows"
              style="width: 100%"
              border
            >
              <el-table-column
                fixed
                type="index"
                label="序号"
                width="150"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="150"
                sortable
              />
              <el-table-column
                prop="description"
                label="描述"
                sortable
              />

              <el-table-column
                fixed="right"
                label="操作"
                width="150"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="AssignPerm(scope.row.id)"
                  >
                    分配权限
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="EditRole(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="deleteRole(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
            <el-pagination
              align="right"
              :page-size="pageConfig.pagesize"
              layout="prev, pager, next"
              :total="$store.state.role.Allroles.total"
              :current-page.sync="pageConfig.page"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="Company.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="Company.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="Company.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="Company.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <el-dialog :title="title" :visible="showDialog">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog title="分配权限" :visible="isshowPerm" @close="isPermEsc">
        <el-tree ref="PermTree" :data="PermList" :props="{label:'name'}" default-expand-all show-checkbox check-strictly node-key="id" />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="isPermEsc">取消</el-button>
            <el-button size="small" type="primary" @click="isPermOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { Get_roledetails, get_All_role, Update_assignPrem } from '@/api/role'
import { tranListToTreeData } from '@/utils/tranListToTreeData.js'
import { getPermissionList } from '@/api/permisson'
// import { Add } from '@/api/debug'
export default {
  data() {
    const checkNode = async(rules, val, callback) => {
      const { rows } = await get_All_role({ page: 1, pagesize: this.$store.state.role.Allroles.total })
      this.roleForm.permIds ? callback() : (rows.some(item => item.name === val) ? callback(new Error(`角色名称已经存在!`)) : callback())
    }
    return {
      RoleID: '',
      PermList: [],
      isshowPerm: false,
      title: '新增角色',
      Allroles: [],
      Company: {},
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      pageConfig: {
        page: 1,
        pagesize: 5
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 16, message: '角色名称要求1-16个字符', trigger: 'blur' },
          { validator: checkNode, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '描述要求1-50个字符', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    // Add(17, '604e21feb205b95968e13129')
    await this.$store.dispatch('role/get_company', this.$store.state.user.userInfo.companyid)
    await this.$store.dispatch('role/get_All_role', this.pageConfig)
    this.Company = this.$store.state.role.Company
    this.GetALLPerm()
  },
  methods: {
    async AssignPerm(id) {
      const { permIds } = await Get_roledetails(id)
      this.RoleID = id
      this.isshowPerm = true
      this.$nextTick(() => {
        this.$refs.PermTree.setCheckedKeys(permIds)
      })
    },
    async GetALLPerm() {
      this.PermList = tranListToTreeData(await getPermissionList(), '0')
    },
    isPermEsc() {
      this.$refs.PermTree.setCheckedKeys([])
      this.isshowPerm = false
    },
    async isPermOK() {
      await Update_assignPrem({
        id: this.RoleID,
        permIds: this.$refs.PermTree.getCheckedKeys()
      })
      this.$message.success('修改成功')
      this.isshowPerm = false
    },
    async get_All_role() {
      if (this.$store.state.role.Allroles.rows.length <= 1 && this.pageConfig.page !== 1) {
        this.pageConfig.page -= 1
      }
      await this.$store.dispatch('role/get_All_role', this.pageConfig)
    },
    AddshowFn() {
      this.title = '新增角色'
      this.showDialog = true
    },
    btnCancel() {
      this.$refs['roleForm'].resetFields()
      this.roleForm = {}
      this.showDialog = false
    },
    async btnOK() {
      this.$refs['roleForm'].validate(async(valid) => {
        if (valid) {
          if (this.roleForm.permIds) {
            await this.$store.dispatch('role/Update_role', this.roleForm)
          } else {
            await this.$store.dispatch('role/Add_role', this.roleForm)
          }
          this.$message({
            message: '操作成功!',
            type: 'success'
          })
          await this.get_All_role()
          this.$refs['roleForm'].resetFields()
          this.roleForm = {}
          this.showDialog = false
        } else {
          return false
        }
      })
    },
    async deleteRole(row) {
      await this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await this.$store.dispatch('role/Delete_role', row.id)
      await this.get_All_role()
      this.$message({
        message: '删除成功!',
        type: 'success'
      })
    },
    async EditRole(row) {
      this.title = '编辑角色'
      const res = await Get_roledetails(row.id)
      this.roleForm = res
      this.showDialog = true
    },
    async  handleCurrentChange(newpage) {
      this.pageConfig.page = newpage
      await this.$store.dispatch('role/get_All_role', this.pageConfig)
    }
  }
}
</script>

<style  scoped>
.addbtn{
  margin-bottom: 20px;
  margin-top: 20px;
}

</style>
